import { http } from '@kit.NetworkKit'

let httpRequest = http.createHttp()

function request<T>(url: string, method: http.RequestMethod, params?: Record<string, any>): Promise<T> {
  return new Promise<T>((resolve, reject) => {
    const token = AppStorage.get<string>('token')
    const headers: Record<string, string> = { 'Content-Type': 'application/json' }
    if (token) {
      headers['X-Hioshop-Token'] = token
    }

    let requestUrl = url
    if (params && (method === http.RequestMethod.GET || method === http.RequestMethod.DELETE)) {
      requestUrl += "?" + Object.keys(params).map((k) => `${k}=${encodeURIComponent(params[k])}`).join('&')
    }

    httpRequest.request(requestUrl, {
      method,
      header: headers,
      extraData: method === http.RequestMethod.POST ? JSON.stringify(params || {}) : undefined
    }).then((res) => {
      if (res.responseCode >= 200 && res.responseCode < 300) {
        resolve(JSON.parse(res.result as string))
      } else {
        reject(new Error(`网络错误: ${res.responseCode}，响应: ${res.result}`))
      }
    }).catch((e: Error) => {
      reject(e)
    })
  })
}

export function get<T>(url: string, params?: Record<string, any>): Promise<T> {
  return request<T>(url, http.RequestMethod.GET, params)
}

export function post<T>(url: string, params?: Record<string, any>): Promise<T> {
  return request<T>(url, http.RequestMethod.POST, params)
}

export function del<T>(url: string, params?: Record<string, any>): Promise<T> {
  return request<T>(url, http.RequestMethod.DELETE, params)
}